<template>
  <div v-loading="loading" :class="{'mobile-detail-wrap':showMobilePage}" class="app-main project-detail">
    <template v-if="costPageAuth">
      <div class="project-info mobile-small-padding">
        <costInfo :detail-data="detailData" style="margin-bottom: 26px;"/>
        <orderInfo :detail-data="orderInfoData" :cost-data="detailData" @relatedOrder="relatedOrderDialog" @cancelRelated="cancelRelated" />
      </div>
      <fixed-pagination>
        <div v-if="!showMobilePage" class="center">
          <el-button v-if="canSettlement(detailData)" type="primary" size="small" style="margin-right: 12px" @click="toSettlement"><span class="font-size-14">发起结算</span></el-button>
          <MoreOperateBtn v-if="canApproval(detailData) || canApprovalCancel(detailData) || canEdit(detailData) || canChangeApprover" class="more-btn-group">
            <el-dropdown-item v-if="canApproval(detailData)" style="width:80px;text-align: center" @click.native="costApprovalDialog(-1, detailData)">
              <div>审批</div>
            </el-dropdown-item>
            <el-dropdown-item v-if="canApprovalCancel(detailData)" style="width:80px;text-align: center" @click.native="costApprovalDialog(0, detailData)">
              <div>作废审批</div>
            </el-dropdown-item>
            <el-dropdown-item v-if="canEdit(detailData)" style="width:80px;text-align: center" @click.native="openDialog('edit')">
              <div>编辑</div>
            </el-dropdown-item>
            <el-dropdown-item v-if="canChangeApprover" style="width:80px;text-align: center" @click.native="handleApproverChange">
              <div>转交</div>
            </el-dropdown-item>
          </MoreOperateBtn>
          <!--
          <el-button v-if="canApproval(detailData)" type="primary" size="small" @click="costApprovalDialog(-1, detailData)"><span class="font-size-14">审批</span></el-button>
          <el-button v-if="canApprovalCancel(detailData)" type="danger" plain size="small" @click="costApprovalDialog(0, detailData)"><span class="font-size-14">作废审批</span></el-button>
          <el-button v-if="canEdit(detailData)" type="info" size="small" class="cancel-btn-style" @click="openDialog('edit')"><span class="font-size-14">编辑</span></el-button>
          -->
          <el-button type="info" class="cancel-btn-style" size="small" @click="toBack"><span class="font-size-14">返回</span></el-button>
        </div>
        <div v-else class="center">
          <MoreOperateBtn v-if="canApproval(detailData) || canApprovalCancel(detailData) || canSettlement(detailData) || canEdit(detailData) || canChangeApprover" class="mobile-btn-flex" style="margin-right: 16px">
            <el-dropdown-item v-if="canApproval(detailData)" style="width:80px;text-align: center" @click.native="costApprovalDialog(-1, detailData)">
              <div>审批</div>
            </el-dropdown-item>
            <el-dropdown-item v-if="canApprovalCancel(detailData)" style="width:80px;text-align: center" @click.native="costApprovalDialog(0, detailData)">
              <div>作废审批</div>
            </el-dropdown-item>
            <el-dropdown-item v-if="canSettlement(detailData)" style="width:80px;text-align: center" @click.native="toSettlement">
              <div>发起结算</div>
            </el-dropdown-item>
            <el-dropdown-item v-if="canChangeApprover" style="width:80px;text-align: center" @click.native="handleApproverChange">
              <div>转交</div>
            </el-dropdown-item>
            <el-dropdown-item v-if="canEdit(detailData)" style="width:80px;text-align: center" @click.native="openDialog('edit')">
              <div>编辑</div>
            </el-dropdown-item>
          </MoreOperateBtn>
          <el-button type="info" class="cancel-btn-style" size="small" @click="toBack"><span class="font-size-14">返回</span></el-button>
        </div>
      </fixed-pagination>
    </template>
    <div v-else class="empty-container-noauth">
      <img :src="emptyImg" alt="">
      <div class="empty-text">暂无权限</div>
    </div>
    <CreateEditCost ref="createEditCost" :cost-data="detailData" :type="opreateType" :cost-belong-type="detailData.costBelong" :page-from="isMengli" @handleClose="handleClose" @submit="getCostDetail" />
    <RelatedOrderDialog ref="relatedOrder" :related-order-id="relatedOrderId" :cost-id="costId" @relatedOrder="relatedOrderSubmit"/>
    <CostApprovalDialog
      ref="costApproval"
      :cost-ids="costId.toString()"
      :type="approvalType"
      :is-batch="0"
      @costApprovalhandle="relatedOrderSubmit" />
    <!-- 人员转交 -->
    <ApproverChange
      ref="approverChangeDialog"
      :business-type="BUSINESS_TYPE.COST"
      :ids="costId"
      append-to-body
      @changeCallBack="getCostDetail"
    />
  </div>
</template>

<script>
// 组件
import CreateEditCost from '@/components/Cost/createCost';
import RelatedOrderDialog from '@/components/Cost/relatedOrderDialog';
import costInfo from './costInfo';
import orderInfo from './orderInfo';
import ApproverChange from '@/components/Common/auditProcess/approverChange';
// assets
import emptyImg from '@/assets/empty-data-icon.png';
// api
import { getCostDetail, cancelRelated } from '@/api/costManage';
import { getOrderInfo } from '@/api/order';
import { getProjectOrder } from '@/api/project';

import { hasRouteAuth } from '@/utils/permission';
import { BUSINESS_TYPE } from '@/utils/const/process';
import { mapState } from 'vuex';
import isAdmin from '@/mixins/isAdmin';
import costSet from '@/mixins/costSet';
import mobileCreate from '@/mixins/mobileCreate';
import { SETTLEMENT_STATUS, APPROVAL_STATUS, BELONG, SEALING_STATUS } from '@/utils/const/cost';

export default {
  components: {
    costInfo,
    orderInfo,
    CreateEditCost,
    ApproverChange,
    RelatedOrderDialog
  },
  mixins: [
    costSet,
    isAdmin,
    mobileCreate],
  data() {
    return {
      BUSINESS_TYPE,
      emptyImg,
      costId: 0,
      detailData: {},
      orderInfoData: {},
      loading: false,
      costPageAuth: true,
      opreateType: '',
      relatedOrderId: 0,
      approvalType: -1
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage,
      'userInfo': state => state.user.userInfo
    }),
    isMengli() {
      return [2, 3, 4].includes(this.detailData.costBelong) ? 'mengli' : '';
    },
    canChangeApprover() {
      return (hasRouteAuth('crm:cost:approverChange') || this.detailData.creatorId === this.userInfo.id) && [0, 2].includes(this.detailData.settlementStatus);
    }
  },
  created() {
    const { id = '' } = this.$route.params;
    this.costId = Number(id);
    this.getCostDetail();
  },
  methods: {
    canSettlement({ settlementStatus: sStatus, costBelong }) {
      // 成本结算状态为待结算
      return sStatus === SETTLEMENT_STATUS.TO_BE_SETTLED;
    },
    /*
      settlementStatus-sStatus 结算状态：0-待结算 1-已完成 2-结算中 5-已忽略
      relatedOrderId 关联订单id
      costBelong 成本来源：0-渠道订单 1-项目订单 2-形象授权 3-营销授权 4-电商销售
      approvalStatus-aStatus 成本审核状态：0-待审批 1-已通过 2:-已拒绝
      sealBillType 封账状态
      APPROVAL_STATUS 成本审批状态：PASS-通过
      SETTLEMENT_STATUS 成本结算状态：TO_BE_SETTLED-待结算 IGNORED-已忽略 COMPLETED-已完成
      orderInfoData.orderStatus 渠道订单状态： 0-草稿中 1-待发布 2-待核算 3-待审核 4-待封账 5-封账中 6-已封账 7-已完成
        还有个项目渠道单但是没有orderStatus
      BELONG PROJECT_CHANNEL-项目渠道单 PROJECT-项目订单
      SEALING_STATUS 成本封账状态：SEALING-封账中
    */
    canEdit({ settlementStatus: sStatus, relatedOrderId, costBelong, approvalStatus: aStatus, sealBillType }) {
      // 成本审批状态：待审批 or 拒绝
      // AND 拥有 crm:cost:edit 权限
      // AND (
      //  如果没有关联订单：则成本结算状态要为 待结算、已忽略或已完成
      //  如果有关联订单：则订单状态不能为已封存  且 成本结算状态要为 待结算或已忽略
      // )
      // AND 成本封账状态必须为待封账

      // v3.2.9 去除成本来源不能为项目订单和项目渠道单的限制

      /* return aStatus !== APPROVAL_STATUS.PASS && ((hasRouteAuth('crm:cost:edit') || this.isAdmin) &&
      ((sStatus === SETTLEMENT_STATUS.TO_BE_SETTLED || sStatus === SETTLEMENT_STATUS.IGNORED || sStatus === SETTLEMENT_STATUS.COMPLETED) && !relatedOrderId) ||
      (relatedOrderId &&
      ![5, 6, 7].includes(this.orderInfoData.orderStatus) &&
      (sStatus === SETTLEMENT_STATUS.TO_BE_SETTLED || sStatus === SETTLEMENT_STATUS.IGNORED))) &&
      sealBillType !== SEALING_STATUS.COMPLETED && sealBillType !== SEALING_STATUS.SEALING; */
      return aStatus !== APPROVAL_STATUS.PASS && (
        (hasRouteAuth('crm:cost:edit') || this.isAdmin) &&
        (!relatedOrderId && [SETTLEMENT_STATUS.TO_BE_SETTLED, SETTLEMENT_STATUS.IGNORED].includes(sStatus)) ||
        (relatedOrderId && this.detailData.relatedProjectStatus !== 5 && [SETTLEMENT_STATUS.TO_BE_SETTLED, SETTLEMENT_STATUS.IGNORED].includes(sStatus))
      ) && ![SEALING_STATUS.COMPLETED, SEALING_STATUS.SEALING].includes(sealBillType);
    },
    // 获取成本详情
    getCostDetail() {
      this.loading = true;
      const params = { costId: this.costId };
      getCostDetail(params).then(res => {
        this.loading = false;
        if (res.code === 200) {
          this.detailData = res.data;
          const { relatedOrderId, costBelong } = this.detailData;
          // 有关联订单id则请求关联订单的详情
          if (relatedOrderId) {
            this.relatedOrderId = relatedOrderId;
            this.getOrderDetail(relatedOrderId, costBelong);
          }
        }
      }).catch((e) => {
        this.loading = false;
      });
    },
    // 获取关联订单详情
    getOrderDetail(id, costBelong) {
      this.relatedOrderId = id;
      // costBelong 0:渠道订单 1:项目订单 2:商务订单 3:营销授权 5:项目渠道单
      let fn;
      if (costBelong === BELONG.CHANNEL) {
        fn = getOrderInfo;
      } else if (costBelong === BELONG.PROJECT_CHANNEL) {
        fn = getProjectOrder;
      } else {
        // 有关联id 无需请求接口的情况，将关联订单id和关联的订单编码赋值给订单对象 用于后续界面展示
        this.orderInfoData.id = this.relatedOrderId;
        this.orderInfoData.orderNum = this.detailData.relatedOrderNum;
        return;
      }
      fn(id).then(res => {
        this.loading = false;
        if (res.code === 200) {
          const { data, data: { orderInfo: orderInfoData }} = res;
          orderInfoData.orderNum = orderInfoData.orderId;
          this.orderInfoData = orderInfoData;
          if (this.orderInfoData.orderOperator && this.orderInfoData.orderOperator.length) {
            this.orderInfoData.orderOperatorStr = this.orderInfoData.orderOperator.map(i => i.userName).join(',');
          }
          this.orderInfoData.accountNameOrganization = data.accountNameOrganization;
          this.orderInfoData.accountNamePlatform = data.accountNamePlatform;
          this.orderInfoData.orderStatus = data.orderStatus;
        }
      }).catch((e) => {
        this.loading = false;
      });
    },
    // 跳转到供应商结算页 id: 供应商id costItemId:传成本项id，costId:成本id，relatedOrderId:关联订单id, name: 成本项名称
    toSettlement() {
      const { relatedOrderId, costItemId, supplierId, costItemName } = this.detailData;
      if (!supplierId) {
        this.$message.warning('该成本未填供应商，无法发起结算');
        return false;
      }
      this.$router.push({
        name: 'supplierCreate', // supplierDetail
        query: {
          id: supplierId, // 供应商id，查找信息
          // （第一步）成本选择阶段
          costItemId, // 成本项id，选中该成本项
          name: costItemName, // 成本项名称，选中该成本项
          // （第二步）审核项选择阶段
          relatedOrderId, // 关联订单id，选中该关联订单（如果有的话）
          costId: this.costId, // 成本id，选中该成本
          orderId: this.detailData.relatedOrderNum || '', // 订单编号，查找该订单，并选中该订单
          costBelong: this.detailData.costBelong // 成本归属，选中该成本归属
        }
      });
    },
    // 返回
    toBack() {
      this.$router.push({
        name: 'costManageList'
      });
    },
    // 打开弹窗用于新增或修改 编辑，type: edit
    openDialog(type) {
      this.opreateType = type;
      // this.$refs.createEditCost.openDialog(type === 'edit' && this.detailData);
      this.$refs.createEditCost.openDialog(type === 'edit' && this.detailData.costBelong);
      // this.$refs.createEditCost.formatSupplierName(this.detailData.supplierId, this.detailData.supplierName);
    },
    // 转交
    handleApproverChange() {
      this.$refs['approverChangeDialog'].dialogVisible = true;
    },
    handleClose(value) {
      this.opreateType = value;
    },
    // 取消关联订单
    cancelRelated() {
      this.$confirm('请确定是否取消关联订单', {
        confirmButtonText: '确定',
        type: 'warning',
        showClose: false,
        center: true,
        iconClass: 'charge-icon',
        customClass: 'del-message del-message-cancel'
      }).then(() => {
        const { costId } = this;
        cancelRelated(costId).then(res => {
          this.$message.success('取消关联成功');
          this.orderInfoData = {};
          this.relatedOrderId = 0;
          this.getCostDetail();
        }).catch(err => {
          console.error(err);
        });
      }).catch(() => {
        return false;
      });
    },
    // 打开关联订单弹窗
    relatedOrderDialog() {
      this.$refs.relatedOrder.openDialog();
    },
    relatedOrderSubmit() {
      this.getCostDetail();
    }
  }
};
</script>

<style lang="scss" scoped>
.project-detail {
  margin: 0;
  border-radius: none;
  .project-info {
    margin: 16px;
    background-color: #fff;
    min-height: calc(100vh - 116px);
    padding: 16px 24px;
  }
  &::v-deep {
    .el-col {
      .el-form-item {
        margin-bottom: 0;
      }
      .el-form-item__content {
        border-right: 1px solid #EBEEFD;
      }
      &:nth-child(3n) {
        .el-form-item__content {
          border-right: none;
        }
      }
      &:last-child {
        .el-form-item__content {
          border-right: none;
        }
      }
    }
  }
}
.empty-container-noauth {
  text-align: center;
  position: relative;
  margin-top: 20px;
  box-shadow: 0px 7px 13px 0px #dde1ea;
  border-radius: 12px;
  background-color: #fff;
  padding: 100px 24px;
  img {
    width: 90px;
  }
  .empty-text {
    color: #999;
    max-width: 300px;
    font-size: 14px;
    margin: 0 auto;
  }
}
.font-size-14 {
  font-size: 14px;
}
.el-button--danger.is-plain{
  border-color: #F56C6C;
}
.mobile-detail-wrap {
  .project-info {
    margin: 0;
    padding: 0;
    .mobile-detail-wrap {
      margin: 0 !important;
    }
  }
}
.more-btn-group {
  ::v-deep {
    .more-btn {
      padding: 8px 12px;
      width: auto;
    }
  }
}
</style>
